---
title: Guide Documents > S/W Development Kit > Mockup Simulator
---
import { Tabs } from 'nextra/components'

## Outline
<Tabs items={['Configuration', 'Build Script', 'Generated SDK Library']}>
  <Tabs.Tab>
```typescript copy filename="nestia.config.ts" showLineNumbers {19}
import { INestiaConfig } from "@nestia/sdk";
import { NestFactory } from "@nestjs/core";
// import { FastifyAdapter } from "@nestjs/platform-fastify";

import { YourModule } from "./src/YourModule";

const NESTIA_CONFIG: INestiaConfig = {
  input: async () => {
    const app = await NestFactory.create(YourModule);
    // const app = await NestFactory.create(YourModule, new FastifyAdapter());
    // app.setGlobalPrefix("api");
    // app.enableVersioning({
      //     type: VersioningType.URI,
    //     prefix: "v",
    // })
    return app;
  },
  output: "src/api",
  simulate: true, // supports simulation mode
  distribute: "packages/api",
  e2e: "test",
};
export default NESTIA_CONFIG;
```
  </Tabs.Tab>
  <Tabs.Tab>
```bash filename="Terminal" showLineNumbers {}
npx nestia sdk
npx nestia sdk --config nestia.config.ts --project tsconfig.json
```
  </Tabs.Tab>
  <Tabs.Tab>
```typescript filename="src/api/functional/bbs/articles/index.ts" showLineNumbers {19-34, 63-64 66-85}
/**
 * Update an article.
 *
 * @param section Section code
 * @param id Target article ID
 * @param input Content to update
 * @returns Updated content
 *
 * @controller BbsArticlesController.update()
 * @path PUT /bbs/:section/articles/:id
 * @nestia Generated by Nestia - https://github.com/samchon/nestia
 */
export async function update(
  connection: IConnection,
  section: string,
  id: string & Format<"uuid">,
  input: update.Input,
): Promise<update.Output> {
  return !!connection.simulate
    ? update.simulate(connection, section, id, input)
    : PlainFetcher.fetch(
        {
          ...connection,
          headers: {
            ...connection.headers,
            "Content-Type": "application/json",
          },
        },
        {
          ...update.METADATA,
          path: update.path(section, id),
        } as const,
        input,
      );
}
export namespace update {
  export type Input = Primitive<IBbsArticle.IStore>;
  export type Output = Primitive<IBbsArticle>;

  export const METADATA = {
    method: "PUT",
    path: "/bbs/articles/:section/:id",
    request: {
      type: "application/json",
      encrypted: false,
    },
    response: {
      type: "application/json",
      encrypted: false,
    },
    status: null,
  } as const;

  export const path = (
    section: string,
    id: string & Format<"uuid">,
  ): string => {
    return `/bbs/${encodeURIComponent(
      section ?? "null",
    )}/articles/${encodeURIComponent(id ?? "null")}`;
  };

  export const random = (g?: Partial<typia.IRandomGenerator>): Output =>
    typia.random<Output>(g);

  export const simulate = async (
    connection: IConnection,
    section: string,
    id: string & Format<"uuid">,
    input: update.Input,
  ): Promise<Output> => {
    const assert = NestiaSimulator.assert({
      method: METHOD,
      host: connection.host,
      path: path(section, id),
    });
    assert.param("section")("string")(() => typia.assert(section));
    assert.param("id")("uuid")(() => typia.assert(id));
    assert.body(() => typia.assert(input));
    return random(
      typeof connection.simulate === "object" && connection.simulate !== null
        ? connection.simulate
        : undefined,
    );
  };
}
```
  </Tabs.Tab>
</Tabs>

Nestia SDK library supports Mockup simulator.

When generating [SDK library](./sdk), if you configure `simulate` property of `nestia.config.file` to be `true`, newly generated SDK library will support mockup simulation mode for frontend developers. With the mockup simulator, frontend developers can simulate NestJS backend server with internal mock functions, instead of connecting to the real backend server.

Therefore, with the mockup simulator, frontend development can be started even when the backend server is not ready yet. Mockup simulator of Nestia SDK will replace the real backend server, validating request data, and returning mockup data as response.

Within framework of backend developers, they also do not need to be suffered from the mock-up data composition. Also, as `nestia` can automatically generate [e2e test functions](e2e), backend developers can concentrated only on the business logic.




## Configuration
<Tabs items={[
  <code>nestia.config.ts</code>, 
  <code>INestiaConfig.ts</code>,
]}>
  <Tabs.Tab>
```typescript copy filename="nestia.config.ts" showLineNumbers {19}
import { INestiaConfig } from "@nestia/sdk";
import { NestFactory } from "@nestjs/core";
// import { FastifyAdapter } from "@nestjs/platform-fastify";

import { YourModule } from "./src/YourModule";

const NESTIA_CONFIG: INestiaConfig = {
  input: async () => {
    const app = await NestFactory.create(YourModule);
    // const app = await NestFactory.create(YourModule, new FastifyAdapter());
    // app.setGlobalPrefix("api");
    // app.enableVersioning({
    //     type: VersioningType.URI,
    //     prefix: "v",
    // })
    return app;
  },
  output: "src/api",
  simulate: true, // supports simulation mode
  distribute: "packages/api",
  e2e: "test",
};
export default NESTIA_CONFIG;
```
  </Tabs.Tab>
  <Tabs.Tab>
```typescript filename="INestiaConfig.ts" showLineNumbers {10-29, 52-65}
import type { INestApplication } from "@nestjs/common";
import type { OpenApi } from "@samchon/openapi";

/**
 * Definition for the `nestia.config.ts` file.
 *
 * @author Jeongho Nam - https://github.com/samchon
 */
export interface INestiaConfig {
  /**
   * Accessor of controller classes.
   *
   * You can specify it within two ways
   *
   *   - Asynchronous function returning `INestApplication` instance
   *   - Specify the path or directory of controller class files
   */
  input:
    | (() => Promise<INestApplication>)
    | INestiaConfig.IInput
    | string[]
    | string;

  /**
   * Output directory that SDK would be placed in.
   *
   * If not configured, you can't build the SDK library.
   */
  output?: string;

  /**
   * Building `swagger.json` is also possible.
   *
   * If not specified, you can't build the `swagger.json`.
   */
  swagger?: INestiaConfig.ISwaggerConfig;

  /**
   * Target directory that SDK distribution files would be placed in.
   *
   * If you configure this property and runs `npx nestia sdk` command,
   * distribution environments for the SDK library would be generated.
   *
   * After the SDK library generation, move to the `distribute` directory,
   * and runs `npm publish` command, then you can share SDK library with
   * other client (frontend) developers.
   *
   * Recommend to use `"packages/api"` value.
   */
  distribute?: string;

  /**
   * Allow simulation mode.
   *
   * If you configure this property to be `true`, the SDK library would be contain
   * simulation mode. In the simulation mode, the SDK library would not communicate
   * with the real backend server, but just returns random mock-up data
   * with requestion data validation.
   *
   * For reference, random mock-up data would be generated by `typia.random<T>()`
   * function.
   *
   * @default false
   */
  simulate?: boolean;

  /**
   * Target directory that e2e test functions would be placed in.
   *
   * If you configure this property and runs `npx nestia e2e` command,
   * `@nestia/sdk` will analyze your NestJS backend server code, and
   * generates e2e test functions for every API endpoints.
   *
   * If not configured, you can't run `npx nestia e2e` command.
   */
  e2e?: string;

  /**
   * Whether to use propagation mode or not.
   *
   * If being configured, interaction functions of the SDK library would
   * perform the propagation mode. The propagation mode means that never
   * throwing exception even when status code is not 200 (or 201), but just
   * returning the {@link IPropagation} typed instance, which can specify its body
   * type through discriminated union determined by status code.
   *
   * @default false
   */
  propagate?: boolean;

  /**
   * Whether to clone DTO structures or not.
   *
   * If being configured, all of DTOs used in the backend server would be cloned
   * into the `structures` directory, and the SDK library would be refer to the
   * cloned DTOs instead of the original.
   *
   * @default false
   */
  clone?: boolean;

  /**
   * Whether to wrap DTO by primitive type.
   *
   * If you don't configure this property as `false`, all of DTOs in the
   * SDK library would be automatically wrapped by {@link Primitive} type.
   *
   * For refenrece, if a DTO type be capsuled by the {@link Primitive} type,
   * all of methods in the DTO type would be automatically erased. Also, if
   * the DTO has a `toJSON()` method, the DTO type would be automatically
   * converted to return type of the `toJSON()` method.
   *
   * @default true
   */
  primitive?: boolean;

  /**
   * Whether to assert parameter types or not.
   *
   * If you configure this property to be `true`, all of the function
   * parameters of SDK library would be checked through
   * [`typia.assert<T>()` function](https://typia.io/docs/validators/assert/).
   *
   * This option would make your SDK library compilation time a little bit slower,
   * but would enahcne the type safety even in the runtime level.
   *
   * @default false
   */
  assert?: boolean;

  /**
   * Whether to optimize JSON string conversion 10x faster or not.
   *
   * If you configure this property to be `true`, the SDK library would utilize the
   * [`typia.assertStringify<T>() function`](https://github.com/samchon/typia#enhanced-json)
   * to boost up JSON serialization speed and ensure type safety.
   *
   * This option would make your SDK library compilation time a little bit slower,
   * but would enhance JSON serialization speed 10x faster. Also, it can ensure type
   * safety even in the runtime level.
   *
   * @default false
   */
  json?: boolean;
}
export namespace INestiaConfig {
  /**
   * List of files or directories to include or exclude to specifying the NestJS
   * controllers.
   */
  export interface IInput {
    /**
     * List of files or directories containing the NestJS controller classes.
     */
    include: string[];

    /**
     * List of files or directories to be excluded.
     */
    exclude?: string[];
  }

  /**
   * Building `swagger.json` is also possible.
   */
  export interface ISwaggerConfig {
    /**
     * Output path of the `swagger.json`.
     *
     * If you've configured only directory, the file name would be the `swagger.json`.
     * Otherwise you've configured the full path with file name and extension, the
     * `swagger.json` file would be renamed to it.
     */
    output: string;

    /**
     * OpenAPI version.
     *
     * If you configure this property to be `2.0` or `3.0`, the newly generated
     * `swagger.json` file would follow the specified OpenAPI version. The newly
     * generated `swagger.json` file would be downgraded from the OpenAPI v3.1
     * specification by {@link OpenApi.downgrade} method.
     *
     * @default 3.1
     */
    openapi?: "2.0" | "3.0" | "3.1";

    /**
     * API information.
     *
     * If omitted, `package.json` content would be used instead.
     */
    info?: Partial<OpenApi.IDocument.IServer>;

    /**
     * List of server addresses.
     */
    servers?: OpenApi.IServer[];

    /**
     * Security schemes.
     *
     * When generating `swagger.json` file through `nestia`, if your controllers or
     * theirs methods have a security key which is not enrolled in here property,
     * it would be an error.
     */
    security?: Record<string, OpenApi.ISecurityScheme>;

    /**
     * List of tag names with description.
     *
     * It is possible to omit this property or skip some tag name even if
     * the tag name is used in the API routes. In that case, the tag name
     * would be used without description.
     *
     * Of course, if you've written a comment like `@tag {name} {description}`,
     * you can entirely replace this property specification.
     */
    tags?: OpenApi.IDocument.ITag[];

    /**
     * Decompose query DTO.
     *
     * If you configure this property to be `true`, the query DTO would be decomposed
     * into individual query parameters per each property. Otherwise you set it to be
     * `false`, the query DTO would be one object type which contains all of query
     * parameters.
     *
     * @default false
     */
    decompose?: boolean;

    /**
     * Operation ID generator.
     *
     * @param props Properties of the API endpoint.
     * @returns Operation ID.
     */
    operationId?(props: {
      class: string;
      function: string;
      method: "HEAD" | "GET" | "POST" | "PUT" | "PATCH" | "DELETE";
      path: string;
    }): string;
  }
}
```
  </Tabs.Tab>
</Tabs>

Make `nestia.config.ts` file and run `npx nestia sdk` command.

At first, create `nestia.config.ts` file through `npx nestia init` command. It would be placed on the top level directory of your NestJS backend project. For reference, `tsconfig.json` file also must be placed in the top level directory, too. After creation, configure the `nestia.config.ts` file referencing above example code and type definition.

At least, you've to configure those three properties. Also, if you've decided to support mockup simulator for frontend developers, I recommend you to configure two properties more, for [automatic e2e functions generation](e2e) and [SDK library distribution](sdk#distribution).

  - Essential
    - `input`: Accessor of controller classes
    - `output`: Path of output directory for SDK library
    - `simulate`: Whether to support simulator or not
  - Recommended
    - `e2e`: Path of output directory for E2E test functions
    - `distribute`: Target directory for SDK library distribution

When you've completed above configuration, just run `npx nestia sdk` command. Then, [SDK library](./sdk) would be generated into the `$config.output` directory, with simulation mode supporting. If you want to generate e2e functions automatically, run `npx nestia e2e` command after.

By the way, `nestia.config.ts` supports alternative options specifying the target controller classes instead of using the `Module` instance. If your backend application server does not have special configuration like `setGlobalPrefix`, `enableVersioning` and `RouterModule`, it is okay to specifying the target controller classes just by writing their file path like below.

<Tabs 
  items={[
    'Module (express)',
    'Module (fastify)',
    'Directory', 
    'Pattern', 
    'Exclude'
  ]}
  defaultIndex={3}>
  <Tabs.Tab>
```typescript copy filename="nestia.config.ts" showLineNumbers {7-15}
import { INestiaConfig } from "@nestia/sdk";
import { NestFactory } from "@nestjs/core";

import { YourModule } from "./src/YourModule";

const NESTIA_CONFIG: INestiaConfig = {
  input: async () => {
    const app = await NestFactory.create(YourModule);
    // app.setGlobalPrefix("api");
    // app.enableVersioning({
    //     type: VersioningType.URI,
    //     prefix: "v",
    // })
    return app;
  },
  output: "src/api",
  simulate: true,
  distribute: "packages/api",
  e2e: "test",
};
export default NESTIA_CONFIG;
```
  </Tabs.Tab>
  <Tabs.Tab>
```typescript copy filename="nestia.config.ts" showLineNumbers {8-16}
import { INestiaConfig } from "@nestia/sdk";
import { NestFactory } from "@nestjs/core";
import { FastifyAdapter } from "@nestjs/platform-fastify";

import { YourModule } from "./src/YourModule";

const NESTIA_CONFIG: INestiaConfig = {
  input: async () => {
    const app = await NestFactory.create(YourModule, new FastifyAdpator());
    // app.setGlobalPrefix("api");
    // app.enableVersioning({
    //     type: VersioningType.URI,
    //     prefix: "v",
    // })
    return app;
  },
  output: "src/api",
  simulate: true,
  distribute: "packages/api",
  e2e: "test",
};
export default NESTIA_CONFIG;
```
  </Tabs.Tab>
  <Tabs.Tab>
```typescript copy filename="nestia.config.ts" showLineNumbers {4-8}
import { INestiaConfig } from "@nestia/sdk";

const NESTIA_CONFIG: INestiaConfig = {
  input: ["src/controllers", "src/fake/controllers", "src/test/controllers"],
  output: "src/api",
  simulate: true,
  distribute: "packages/api",
  e2e: "test",
};
export default NESTIA_CONFIG;
```
  </Tabs.Tab>
  <Tabs.Tab>
```typescript copy filename="nestia.config.ts" showLineNumbers {4}
import { INestiaConfig } from "@nestia/sdk";

const NESTIA_CONFIG: INestiaConfig = {
  input: "src/**/*.controller.ts",
  output: "src/api",
  simulate: true,
  distribute: "packages/api",
  e2e: "test",
};
export default NESTIA_CONFIG;
```
  </Tabs.Tab>
  <Tabs.Tab>
```typescript copy filename="nestia.config.ts" showLineNumbers {4-7}
import { INestiaConfig } from "@nestia/sdk";

const NESTIA_CONFIG: INestiaConfig = {
  input: {
    include: ["src/controllers"],
    exclude: ["src/**/*.fake.ts"],
  },
  output: "src/api",
  simulate: true,
  distribute: "packages/api",
  e2e: "test",
};
export default NESTIA_CONFIG;
```
  </Tabs.Tab>
</Tabs>




## Code Analysis
<Tabs items={['SDK Library Code', 'utils/NestiaSimulator.ts']}>
  <Tabs.Tab>
```typescript filename="src/api/functional/bbs/articles/index.ts" showLineNumbers {19-34, 63-64, 66-85}
/**
 * Update an article.
 *
 * @param section Section code
 * @param id Target article ID
 * @param input Content to update
 * @returns Updated content
 *
 * @controller BbsArticlesController.update()
 * @path PUT /bbs/:section/articles/:id
 * @nestia Generated by Nestia - https://github.com/samchon/nestia
 */
export async function update(
  connection: IConnection,
  section: string,
  id: string & Format<"uuid">,
  input: update.Input,
): Promise<update.Output> {
  return !!connection.simulate
    ? update.simulate(connection, section, id, input)
    : PlainFetcher.fetch(
        {
          ...connection,
          headers: {
            ...connection.headers,
            "Content-Type": "application/json",
          },
        },
        {
          ...update.METADATA,
          path: update.path(section, id),
        } as const,
        input,
      );
}
export namespace update {
  export type Input = Primitive<IBbsArticle.IStore>;
  export type Output = Primitive<IBbsArticle>;

  export const METADATA = {
    method: "PUT",
    path: "/bbs/articles/:section/:id",
    request: {
      type: "application/json",
      encrypted: false,
    },
    response: {
      type: "application/json",
      encrypted: false,
    },
    status: null,
  } as const;

  export const path = (
    section: string,
    id: string & Format<"uuid">,
  ): string => {
    return `/bbs/${encodeURIComponent(
      section ?? "null",
    )}/articles/${encodeURIComponent(id ?? "null")}`;
  };

  export const random = (g?: Partial<typia.IRandomGenerator>): Output =>
    typia.random<Output>(g);

  export const simulate = async (
    connection: IConnection,
    section: string,
    id: string & Format<"uuid">,
    input: update.Input,
  ): Promise<Output> => {
    const assert = NestiaSimulator.assert({
      method: METHOD,
      host: connection.host,
      path: path(section, id),
    });
    assert.param("section")(() => typia.assert(section));
    assert.param("id")(() => typia.assert(id));
    assert.body(() => typia.assert(input));
    return random(
      typeof connection.simulate === "object" && connection.simulate !== null
        ? connection.simulate
        : undefined,
    );
  };
}
```
  </Tabs.Tab>
  <Tabs.Tab>
```typescript filename="NestiaSimulator.ts" showLineNumbers {72-83}
import { HttpError } from "@nestia/fetcher";

import typia from "typia";

export namespace NestiaSimulator {
  export interface IProps {
    host: string;
    path: string;
    method: "GET" | "POST" | "PATCH" | "PUT" | "DELETE";
    contentType: string;
  }

  export const assert = (props: IProps) => {
    return {
      param: param(props),
      query: query(props),
      body: body(props),
    };
  };
  const param =
    (props: IProps) =>
    (name: string) =>
    <T>(task: () => T): void => {
      validate((exp) => `URL parameter "${name}" is not ${exp.expected} type.`)(
        props,
      )(task);
    };

  const query =
    (props: IProps) =>
    <T>(task: () => T): void =>
      validate(
        () => "Request query parameters are not following the promised type.",
      )(props)(task);

  const body =
    (props: IProps) =>
    <T>(task: () => T): void =>
      validate(() => "Request body is not following the promised type.")(props)(
        task,
      );

  const validate =
    (message: (exp: typia.TypeGuardError) => string, path?: string) =>
    (props: IProps) =>
    <T>(task: () => T): void => {
      try {
        task();
      } catch (exp) {
        if (typia.is<typia.TypeGuardError>(exp))
          throw new HttpError(
            props.method,
            props.host + props.path,
            400,
            {
              "Content-Type": props.contentType,
            },
            JSON.stringify({
              method: exp.method,
              path: path ?? exp.path,
              expected: exp.expected,
              value: exp.value,
              message: message(exp),
            }),
          );
        throw exp;
      }
    };
}
```
  </Tabs.Tab>
</Tabs>

Let's read generated SDK library code, and understand which features are supported

At first, you can find that mock-up data is composed by [`typia.random<T>()`](https://typia.io/docs/random) function. Also, simulator function validates `path` parameters and `request body` data through [`typia.assert<T>()`](https://typia.io/docs/validate/assert) function. If the validation fails, 400 status error would be thrown.

At last, if frontend developer turns off simulation mode by configuring `IConnection.simulate` value to be `false`, the SDK library stops NestJS backend server simulating, and just start communicating with the real backend server.